import SockJS from 'sockjs-client'
import Stomp from 'stompjs'

import {Notification} from "element-ui"

import {admin_host,admin_port} from '@/utils/constant'

export var stompClient = null;

export const connectClient = (username) => {         // websocket连接触发函数
    const url = 'http://'+admin_host+':'+admin_port+'/ww-websocket'
    console.log('url：',url)
    const socket = new SockJS(url);
    stompClient = Stomp.over(socket);
    stompClient.connect({},
        // 连接成功后的回调方法
        frame => {
            // Notification.success({
            //     title: '通信状态',
            //     message: '连接成功'
            // })
            // 客户端订阅问候频道，当后端发送消息到/topic/greetings频道上会自动触发此回调函数
            stompClient.subscribe('/topic/greetings', res => {
                // 收到服务端发送消息，客户端收到展示
                Notification.success({
                    title: '系统消息',
                    message: JSON.parse(res.body).content
                })
            })
            stompClient.subscribe('/topic/system/info', res => {
                const data = JSON.parse(res.body)
                // 收到服务端发送消息，客户端收到展示
                Notification.success({
                    duration: 0,        // 不会自动关闭消息框
                    title: '收到【'+data.sender+'】发送通知',
                    message: data.message
                })
            })
            // 发送登录成功
            stompClient.send("/topic/admin/login", {}, JSON.stringify({'name': username}))
        })
}

export const disconnectClient = () => {
    if (stompClient !== null) {
        if(stompClient.connected) {
            stompClient.disconnect()
        }
    }
    Notification.warning({
        title: '通信状态',
        message: '已关闭'
    })
}

